﻿using System;
using System.Security.Cryptography;
using System.Text;
using Abp.Application.Services;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.UI;
using Admin.Entities;
using Admin.Services.Dto.Users;

namespace Admin.Services
{
    [AbpAuthorize]
    public class UserAppService : ApplicationService
    {
        private readonly IRepository<User> _accountRepository;

        public UserAppService(
            IRepository<User> userRepository)
        {
            _accountRepository = userRepository;
        }

        [AbpAllowAnonymous]
        public LoginOutput Login(LoginInput input)
        {
            var password = PasswordHash(input.Password);


            var user = _accountRepository.FirstOrDefault(x =>
                x.Name == input.Name &&
                x.Password == password);
            if (user == null)
                throw new UserFriendlyException("用户名或者密码错误");

            var output = new LoginOutput { User = user.MapTo<UserDto>() };
            return output;
        }

        [AbpAllowAnonymous]
        public RegisterOutput Register(RegisterInput input)
        {

            if (_accountRepository.Count(x => x.Name == input.Name) > 0)
            {
                throw new UserFriendlyException("用户名已存在");
            }

            var user = new User
            {
                Name = input.Name,
                Password = PasswordHash(input.Password),
            };

            user = _accountRepository.Insert(user);
            var output = new RegisterOutput { User = user.MapTo<UserDto>() };
            return output;
        }




        private string PasswordHash(string password)
        {
            var buffer = Encoding.Default.GetBytes(password);
            using (var md5 = new MD5CryptoServiceProvider())
            {
                buffer = md5.ComputeHash(buffer);
            }
            return Convert.ToBase64String(buffer);
        }



    }
}